package com.example.discover.viewmodel

import android.util.Log
import com.example.discover.dao.SubjectDao
import com.example.featuresdk.viewmodel.BasicViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import java.util.*
import javax.inject.Inject

@HiltViewModel
class DiscoverListViewModel
@Inject constructor(private val subjectDao: SubjectDao) : BasicViewModel(){

    val uiState = DiscoveryListState()

    init {
        launch {
            subjectDao.getAll().collect { subjects ->
                subjects.forEach {
                    val capital = it.title.uppercase(Locale.getDefault())
                    if(uiState.groupedTopics.containsKey(capital)){
                        uiState.groupedTopics[capital]!!.add(it)
                    }else{
                        uiState.groupedTopics[capital] = mutableListOf(it)
                    }
                }
            }
        }
    }

    override fun onCleared() {
        Log.w("*****ViewModel.onCleared()",this.javaClass.canonicalName)
        super.onCleared()
    }
}